package com.duyulong.demo.controller;

import com.duyulong.demo.entity.User;
import com.duyulong.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
public class AuthController {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    @GetMapping("/register")
    public String registerPage(Model model) {
        if (!model.containsAttribute("user")) {
            model.addAttribute("user", new User());
        }
        return "register";
    }
    
    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") User user,
                             BindingResult result,
                             RedirectAttributes redirectAttributes) {
        // 验证用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            result.rejectValue("username", "error.user", "用户名已被使用");
        }
        
        // 验证邮箱是否已存在
        if (user.getEmail() != null && !user.getEmail().isEmpty() 
            && userRepository.existsByEmail(user.getEmail())) {
            result.rejectValue("email", "error.user", "邮箱已被使用");
        }
        
        if (result.hasErrors()) {
            return "register";
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        try {
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败，请稍后重试");
            return "redirect:/register";
        }
    }
    
    @GetMapping("/api/auth/check")
    @ResponseBody
    public boolean checkLoginStatus(@SessionAttribute(value = "user", required = false) User user) {
        return user != null;
    }
} 